package com.zeei.ems.base.security.handler;

import com.zeei.ems.base.security.respone.CommonCode;
import com.zeei.ems.base.security.respone.CommonResult;
import com.zeei.ems.base.util.JsonUtil;
import com.zeei.ems.meet.util.JackSonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {

        log.error("登录失败："+e);

        //返回json数据
        CommonResult commonResult = new CommonResult(CommonCode.AUTH_FAILED);
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
       //塞到HttpServletResponse中返回给前端
        httpServletResponse.getWriter().write(JackSonUtil.writeValueAsString(commonResult));
    }
}